<template>
  <div>
    <a-tree :tree-data="Tabledata" :showLine="false" showIcon :load-data="onLoadData">
      <template slot="table">
        <a-icon type="table" />
      </template>
      <template slot="eye">
        <a-icon type="eye" />        
      </template>
    </a-tree>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
  export default {
    data() {
      return {
        Tabledata: []
      }
    },
    computed: {},
    props: ['queryForm'],
    methods: {
      ...mapActions('sql_query', ['getDataList', 'getDataColumnsList']),
      loadData () {
        this.getDataList({ id: this.queryForm.datasourceId })
        .then(res=>{
          this.Tabledata = res.data.map((item,index) =>{
            if(item.type == 'TABLE') {
              return {title: item.name, key:index, slots: { icon: 'table' }}
            } else {
              return {title: item.name, key:index, slots: { icon: 'eye' }}
            }
          })
        })
      },
      onLoadData (treeNode) {
        return new Promise((resolve) => {
          // console.log(treeNode)
          if (treeNode.dataRef.children) {
            resolve()
            return;
          }
          this.getDataColumnsList({tableName: treeNode.dataRef.title, id: this.queryForm.datasourceId  })
            .then(res => {
              treeNode.dataRef.children = this.deal_tree(res.data, treeNode.dataRef.key)
              this.Tabledata = [...this.Tabledata]
              resolve()
            })
            .catch(err => {
              console.error(err)
            })
        })
      },
      deal_tree (list, key) {
        return list.map( (item, index) => {
          return { title: `${item.name}(${item.dataType})`, key: key + '-' + index, isLeaf: true, slots: { icon: undefined } }
        })
      }
    },
    mounted() {
      this.loadData()
    },
  }
</script>

<style scoped>

</style>